package dev.caobaoqi6040.backend.modules.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import dev.caobaoqi6040.backend.modules.user.entity.User;
import dev.caobaoqi6040.backend.modules.user.exception.UserAlreadyException;
import dev.caobaoqi6040.backend.modules.user.repository.UserMapper;
import dev.caobaoqi6040.backend.modules.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * UserServiceImpl
 *
 * @author caobaoqi6040
 * @since 2025/10/9 11:24
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

	private final PasswordEncoder encoder;

	@Override
	public void makeUser(String email, String password) {
		if (!userExist(email)) {
			throw new UserAlreadyException(String.format("user %s already exist", email));
		}
		User user = User.builder()
			.email(email)
			.password(encoder.encode(password))
			.avatar("http://localhost:9000/avatar/caobaoqi6040.jpg")
			.build();
		this.save(user);
	}

	@Override
	public Boolean userExist(String email) {
		var wrapper = Wrappers.lambdaQuery(User.class)
			.eq(User::getEmail, email);
		return this.exists(wrapper);
	}

	@Override
	public User getUserByEmail(String email) {
		var wrapper = Wrappers.lambdaQuery(User.class)
			.eq(User::getEmail, email);
		return this.getOneOpt(wrapper)
			.orElseThrow(() -> new UsernameNotFoundException(String.format("user not found with email %s", email)));
	}
}
